<template>
  <div id="displayer">
    <div class="info">
      <!-- <div class="gauge">
        <Gauge v-bind:width="'280'" v-bind:height="'250'" ref="gauge"></Gauge>
      </div> -->
      <div class="profit-scale">
        <h3>{{task.symbol.toUpperCase()}}</h3>
        <div style="margin: 5px 0;">
          <el-tag
          size="mini"
          :type="task.state == 1 ? 'success':'danger'"
          effect="dark">
          {{task.state == 1 ? '运行中':'已停止'}}
          </el-tag>
        </div>
       
        <h3 class="profit-scale-num" :class="[profitScale > 0 ? 'profit-scale-green':'profit-scale-red']">{{profitScale}}%</h3>
      </div>


        <table class="form-table" cellspacing="0" frame="box" rules="rows">
          <tbody>
            
             <tr>
              <td class="table-item">买进单数上限：</td>
              <td class="table-value">
                <div class="table-text">{{task.buyMoneys.length}}单</div>
              </td>
            </tr>

             <tr>
              <td class="table-item">深度：</td>
              <td class="table-value">
                <div class="table-text">{{task.depth == undefined ? 30 : task.depth}}%</div>
              </td>
            </tr>


           
              <tr>
              <td class="table-item">补单金额：</td>
              <td class="table-value">
                <div class="table-text">{{computedBuyMoneys}}</div>
              </td>
            </tr>
             <tr>
              <td class="table-item">补单价格：</td>
              <td class="table-value">
                <div class="table-text">{{computedBuyPrices}}</div>
              </td>
            </tr>

            <tr>
              <td class="table-item">本轮已补单：</td>
              <td class="table-value">
                <div class="table-text">{{task.buyTradeCount}}单</div>
              </td>
            </tr>
      
       
            <tr>
              <td class="table-item">反弹百分比：</td>
              <td class="table-value">
                <div class="table-text">{{task.reboundPercent}}%</div>
              </td>
            </tr>

             <tr>
              <td class="table-item">止盈百分比：</td>
              <td class="table-value">
                <div class="table-text">{{task.profitPercent}}%</div>
              </td>
            </tr>
            
            <tr>
              <td class="table-item">回降百分比：</td>
              <td class="table-value">
                <div class="table-text">{{task.fallBackPercent}}%</div>
              </td>
            </tr>

             <tr>
              <td class="table-item">累计止盈：</td>
              <td class="table-value">
                <div class="table-text">{{task.loopCount - 1}}单</div>
              </td>
            </tr>

             <tr>
              <td class="table-item">当前持仓金额：</td>
              <td class="table-value">
                 <div class="table-text">{{task.totalMoney}}</div>
              </td>
            </tr>
             <tr>
              <td class="table-item">当前持仓数量：</td>
              <td class="table-value">
                <div class="table-text">{{task.totalAmount}}</div>
              </td>
            </tr>
          </tbody>
        </table>



      <div class="btn-bottom">
        <div class="btn-item">
          <el-button type="danger" style="width:200px;" @click="sellAll" :disabled="disSell" :key="sellAllText">{{sellAllText}}</el-button>
        </div>
        <div class="btn-item">
          <el-button :type="task.state == 1 ? 'danger' : 'success'" style="width:200px;" @click="updateTaskState" >{{task.state == 1 ? '停止任务' : '启动任务'}}</el-button>
        </div>
         <div class="btn-item">
          <el-checkbox v-model="task.stopTrade"  :true-label="1" :false-label="0" @change="onStopTrade">只监控不交易</el-checkbox>
        </div>
        <div class="btn-item">
          <el-checkbox v-model="task.quit"  :true-label="1" :false-label="0" @change="onGoQuit">完成本轮停止任务</el-checkbox>
        </div>
       

      </div>

    </div>
    <div class="right">
       <div class="console" id="console">
        <div style="position:fixed;top:5px;right:14px;">
          <el-button-group class="button-group">
            <el-button size="mini" @click="onScrollClick">{{scrollable ? '禁止滚动':'自动滚动'}}</el-button>
            <el-button icon="el-icon-delete" size="mini" @click="onClearMsg"></el-button>
          </el-button-group>
        </div>
        
        <ul>
          <li v-for="(item,index) in messages" :key="index">
            {{item.datetime}} - {{item.message}}
          </li>
        </ul>
 
      </div>
      <div class="right-kline">
        <div id="tradingKLine" style="width:100%;height:100%;background-color:#171B2B;"></div>
      </div>
    </div>

  </div>
</template>

<script>
import $ from 'jquery';
import Gauge from '../../../components/Gauge'

const { ipcRenderer } =  window.require('electron');
export default {
  name: 'Home',
  components: {
    Gauge
  },
 data(){
   return {
     scrollable:true,
     messageMaxSize:100,
     messageSizeCheckInterval:10000,
     messages:[
       
      

     ],
     task: {
        state:0,
        symbol: "",
        buyTradeCount:0,
        buyMoneys:[{value:''}],
        buyLevel: 3,
        depth:30,
        reboundPercent: 0,
        buyBasePrice:'0',
        profitPercent: 2.5,
        fallBackPercent: 0,
        loopCount:1,
        totalAmount:'0',
        totalMoney:'0',
        sort:0,
        quit:0,
        stopTrade:0
      },
      profitScale:0.0,
      disSell:false,
      sellAllText:'一键卖出',
      klineSymbol:'',
   }
 },
 computed:{
   computedBuyMoneys(){
     let ret = '';
     let arr = this.task.buyMoneys;
     for(let i = 0; i < arr.length; i++){
       let str = '【第'+(i+1)+'单:' + arr[i].value + '】';
       ret += str;
       
     }

     return ret;
   },
   computedBuyPrices(){
     let ret = '';
     if(this.task.buyTradeCount > 0){
       let basePrice = this.task.buyBasePrice;
       let subPercent = this.task.depth / 100;
       let buyCountLimit = this.task.buyMoneys.length;
       let unitPrice = (basePrice * subPercent) / (buyCountLimit - 1);
       for(let i = 0; i < buyCountLimit; i++){
          let str = '【第'+(i+1)+'单:' + (basePrice - (unitPrice * i)).toFixed(8) + '】';
          ret += str;
      }
     }
     return ret;
   },

 },
 watch:{
   klineSymbol(val,oldVal){
      this.renderKline(val);
   }
 },
 methods:{
   updateValue(){
     this.$refs.gauge.updateValue(3);
   },
   scroll(){
     if(this.scrollable){
      let doc = document.querySelector("#console")
     let scrollTop = doc.scrollTop;
     let clientHeight = doc.clientHeight;
     let scrollHeight = doc.scrollHeight;

      if(scrollHeight - clientHeight >= scrollTop){
        doc.scrollTop = (scrollHeight - clientHeight);
      }
     }
     
   },
   onScrollClick(){
     this.scrollable = !this.scrollable;
   },
   onClearMsg(){
     this.messages = [];
   },
    onUpdateItem(){
        ipcRenderer.on('updateItem',(event,id) => {
          this.updateItem(id);
      })
    },
    updateItem(id){
      ipcRenderer.once('getTaskById-res',(event,res)=>{
        console.log('getTaskById-res',res)
          if(res.success){
              let doc = res.data
             if(doc.depth == undefined){
                  doc.depth = 30;
              }
              if(doc.quit == undefined){
                  doc.quit = 0;
              }
              if(doc.stopTrade == undefined){
                  doc.stopTrade = 0;
              }
              this.task = doc;
              this.klineSymbol = doc.symbol;
            }
      })
      ipcRenderer.send('getTaskById',id);
  
    },
    onUpdatePercent(){
        ipcRenderer.on('updatePercent',(event,msg) => {
          // this.$refs.gauge.updateValue(parseFloat(msg.message));
          // this.$refs.gauge.updateValue(parseFloat(msg.message));
          this.profitScale = parseFloat(msg.message);
      })
    },
    sellAll(){
      ipcRenderer.send('sellAll',this.task._id);
      this.disSell = true;
      let seconds = 10;
      let disId = setInterval(()=>{
        this.sellAllText = seconds;
        if(seconds <= 0){
          this.sellAllText = '一键卖出';
          this.disSell = false;
          clearTimeout(disId);
        }
        seconds --;
      },1000)
      

    },
     updateTaskState(){
      ipcRenderer.once('updateTaskState-res',(event,res)=>{
        console.log('updateTaskState-res',res)
         if(res.success){
            if(res.data > 0){
              if(this.task.state == 1){
                  ipcRenderer.send('shutdownTask',this.task._id)
              }else{
                  ipcRenderer.send('startupTask',this.task._id)
              }

            }
          }
      })
      
      ipcRenderer.send('updateTaskState',{_id:this.task._id,state:this.task.state == 0 ? 1 : 0})

    },
    onGoQuit(value){
      ipcRenderer.send('updateQuitState',{_id:this.task._id,state:value})
     
    },
    onStopTrade(value){
        ipcRenderer.once('updateTradeState-res',(event,res)=>{
          ipcRenderer.send('refreshTaskData',this.task._id)
        })
      ipcRenderer.send('updateTradeState',{_id:this.task._id,state:value})

     
    },
    renderKline(symbol){
        new TradingView.widget(
        {
        "autosize": true,
        "symbol": "HUOBI:" + symbol.toUpperCase(),
        "interval": "5",
        "timezone": "Asia/Chongqing",
        "theme": "dark",
        "style": "1",
        "locale": "zh_CN",
        "toolbar_bg": "#f1f3f6",
        "enable_publishing": false,
        "save_image": false,
        "container_id": "tradingKLine"
      }
        );
    }
      
 },
 updated(){
   this.scroll();
 },
 mounted(){
  
  var query=location.search.substring(1);
   let taskId = query.split('=')[1]
  if(taskId){
      this.updateItem(taskId);
  }
 
  
    ipcRenderer.on('message',(event,data) => {
      this.messages.push(data)      
    })
    this.onUpdateItem();
    this.onUpdatePercent();
    setInterval(() => {
      if(this.messages.length > this.messageMaxSize){
        let splitIndex = this.messages.length - this.messageMaxSize;
        this.messages.splice(0,splitIndex)
      }
    }, this.messageSizeCheckInterval);
 }
};
</script>

<style lang="less">
#displayer{
  display:flex;
  width:100vw;
  height:100vh;

  .info{
    height:100vh;
    min-height: 600px;
    width:300px;
    padding:5px;
    background-color: #012456;
    border-right:8px solid #252A44;
    background: -webkit-linear-gradient(bottom,#104C88, #446BA4,#7287B4); /* For Safari 5.1 to 6.0 */
    overflow: auto;
    position:relative;

    .profit-scale{
      text-align:center;
      margin: 30px 0 30px 0;
      color:#fff;
      .profit-scale-num{
        display:inline;
        font-weight:700;
        margin-top:10px;
        font-size:38px;
      }  
       .profit-scale-red{
        color:#FA5252;
      }
       .profit-scale-green{
        color:#12B886;
      }
    }

   
    .form-data{
      color:#fff;
      font-size:16px;
      .form-item{
        height:18px;
        line-height:18px;
        width:250px;
        margin: 8px auto;
        display:flex;
        .item-name{
          width:50%;
          font-weight:bold;
          text-align:left;
        }
        .item-value{
          width:50%;
          font-weight:600;
          text-align:right;
          font-size:14px;
        }
      }
    }

    .form-table{
      width:100%;
      color:#fff;
      font-size:16px;
      font-weight:900;
     
      td{
        height:26px;
        border:1px solid #999;
      }
      
      .table-item{
        width:120px;
      }
      .table-value{
        width:150px;
        text-align:right;
        font-size:15px;
        white-space: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
      }
      .table-text{
        
        width: 156px;
        
      }
    }

    .btn-bottom{
      text-align: center;
      margin-top:10px;
      color:#fff !important;
      position: absolute;
    bottom: 10px;
    width: 285px;
      .btn-item{
        margin: 10px 0;
       .el-checkbox {
          color: #fff;
        }
      }
    }
  }
  .right{
    height:100vh;
    min-height: 600px;
    flex:1;
    // padding:5px;
    background-color:#171B2B;
    color:#B0B8DB;
    overflow-y:auto;
    position:relative;
    display:flex;
    flex-direction:column;

      .console{
        // height:100vh;
        // min-height: 600px;
        flex:1;
        font-size:12px;
        padding:5px;
        background-color:#171B2B;
        color:#B0B8DB;
        overflow-y:auto;
        position:relative;
        }

     .right-kline{
        height:50%;
        width:100%;
         background-color:#171B2B;
         border-top:8px solid #252A44;
      }
  }


}


  .console::-webkit-scrollbar{width:10px;height:8px;}
  .console::-webkit-scrollbar-button{width:10px;height:8}
  .console::-webkit-scrollbar-track{background:0 0}
  .console::-webkit-scrollbar-thumb{background:#383F66;border-radius:5px}
  .console::-webkit-scrollbar-thumb:hover{background-color:#66B1FF}
  .console::-webkit-scrollbar-thumb:active{background-color:#17bbaf}

  
</style>
